#Python's condition statement
When writing programs, we often need to execute different codes according to different situations. For example, in a weather application, if the weather is sunny, it will display "Remember to wear sunglasses when going out"; if it is raining, it will display "Remember to bring an umbrella when going out." This behavior of executing different codes according to conditions is called conditional control.
#Syntax
Python uses if
, elif
and else
to perform conditional judgment. Its basic syntax is as follows:
if condition-1: # If condition-1 is True, then execute code-block-1
code-block-1
elif condition-2: # Otherwise (i.e. condition-1 is False), if condition-2 is True, then execute code-block-2
code-block-2
...
elif condition-n: # Otherwise (i.e. all previous conditions are False), if condition-n is True, execute code-block-n
code-block-n
else: # Otherwise (i.e. all previous conditions are False), execute code block n+1
code-block-n+1
For example:
SUNNY:int = 1
RAINY:int = 2
weather:int = SUNNY
if weather == SUNNY:
print("Remember to wear sunglasses when going out")
elif weather == RAINY:
print("Remember to bring an umbrella when you go out")
#Code block
Python code blocks are separated by indentation, for example:
print("This is the outermost code block") # Block A
if True:
print("This is the code block of the outer if condition") # Block B
if False:
print("This is the code block of the inner if condition") # Block C
print("This is the code block of the inner if condition") # Block C
print("This is the code block of the outer if condition") # Block B
print("This is the outermost code block") # Block A
There is no specific rule for indentation, but four spaces is usually used.
#Conditional expression
In programming, we often encounter some simple conditional judgments, such as "go buy fruit, if there are pineapples, buy two, if not, buy a watermelon".
In some other programming languages, you can use the ternary operator to simplify the operation, such as pineapple_exists ? 2 : 1
(if pineapple_exists
is True
, the result is 2
, otherwise the result is 1
).
There is no ternary operator in Python, you can use if-else
to implement this function:
pineapple_exists:bool = True
count:int = 2 if pineapple_exists else 1 # The result is 2 if pineapple_exists is True, otherwise it is 1
print(count)
#Practise
Please implement the function to determine whether an integer is even or odd, and get the input through input
.
- Integers that are divisible by 2 are even numbers, and integers that are not divisible by 2 are odd numbers.
number:int = int(input("Please enter an integer:"))
if True: # Modify the code here to determine whether number is even or odd
print(number, "is an even number")
else:
print(number, "is an odd number")